/* 
* EncoderHandler.cpp
*
* Created: 10/4/2013 8:05:35 PM
* Author: brodzki
*/

#include "EncoderHandler.h"

void EncoderHandler::initialize()
{
	fst_.ddr.unset_bit(fst_bit_);
	fst_.port.set_bit(fst_bit_);
	
	snd_.ddr.unset_bit(snd_bit_);
	snd_.port.set_bit(snd_bit_);
	
	btn_.ddr.unset_bit(btn_bit_);
	btn_.port.set_bit(btn_bit_);
}

uint8_t EncoderHandler::read()
{
	uint8_t result = neutral;
	uint8_t current = 0;

	if(bit_is_clear(*(btn_.pin.address), btn_bit_))
	{
		for(unsigned int i = 0; i < 65535; ++i)
		{
			if(!bit_is_clear(*(btn_.pin.address), btn_bit_))
				return result;
		}
		result = click;
	}
	else
	{
		if(bit_is_clear(*(fst_.pin.address), fst_bit_))
			current = 1;
		else
			current = 0;

		if(last_ != current)
		{
			if(bit_is_clear(*(fst_.pin.address), fst_bit_))
			{
				if(bit_is_clear(*(snd_.pin.address), snd_bit_))
					result = left;
				else
					result = right;
			}
			else
			{
				if(bit_is_clear(*(fst_.pin.address), snd_bit_))
					result = right;
				else
					result = left;
			}
			last_ = current;
		}
	}
	return result;
}